From zero to practice
Mail: javier.alvarez.liebana@upm.es.
Javier Álvarez Liébana from Carabanchel (Madrid).
Degree in Mathematics (UCM). PhD in Statistics (UGR).
Data visualization and analysis for the Principality of Asturias (2021-2022) during the COVID pandemic
Member of the Spanish Society of Statistics and OR and the Spanish Royal Mathematical Society.
Currently, Assistant Professor at Technical University of Madrid (UPM) and Visiting Researcher at Harvard University.
Take away the fear of programming → learn to program by programming
Understanding basic R concepts from scratch → learning to abstract ideas and algorithms
Utility of programming → reproducible, transparent and maintainable workflows.
Introduction to analysis and preprocessing of data → {tidyverse}.
Introduction to dataviz in R → {ggplot2}
To learn the fundamentals of statistics and Machine Learning. From descriptive analysis to prediction: building our first models.
Quarto. In the slide menu (bottom left) you have an option to download them in pdf in Tools
workbooks folder.cheatsheets-packages folder.Introduction to R and RStudio. Working with projects. First uses of functions and packages. Basic data types
For the course, the only requirements will be:
We will program as we write
R)RStudio) to write itThe R language will be our grammar and spelling (our rules of the game)
Step 1: go to https://cran.r-project.org/ and select your operating system.
Step 2: for Mac, simply click on the .pkg file, and open it once downloaded. For Windows systems, we need to click on install R for the first time and then on Download R for Windows. Once downloaded, open it like any installation file.
Step 3: open the installation executable.
Warning
Whenever you need to download something from CRAN (either R itself or a package), make sure you have an internet connection.
To check the installation, after opening R, you should see the R GUI (Graphical User Interface) with a white screen similar to this (console).
To check the installation, after opening R, you should see the R GUI (Graphical User Interface) with a white screen similar to this (console).
First code: we will assign the value 1 to a variable called a (we will write the code in the console and press “enter”). Then we will do the sum a + b.
To check the installation, after opening R, you should see the R GUI (Graphical User Interface) with a white screen similar to this (console).
First code: we will assign the value 1 to a variable called a (we will write the code in the console and press “enter”). Then we will do the sum a + b.
Note that…
In the console, a number [1] appears: it’s simply an element counter (like counting rows in Word)
RStudio will be the Word we will use to write (what is known as an IDE: Integrated Development Environment).
Step 1: go to the official RStudio website (now called Posit) and select the free download.
Step 2: select the executable that appears according to your operating system.
Step 3: after downloading the executable, open it like any other and let the installation finish.
When you open RStudio you will likely have three windows:
When you open RStudio you will likely have three windows:
When you open RStudio you will likely have three windows:
R is the evolution of the work of Bell Laboratories with the S language, which was brought into the open-source world by Ross Ihaka and Robert Gentleman in the 1990s. The version R 1.0.0 was released on February 29, 2000.
R is the statistical language par excellence, created by and for statisticians, with 6 fundamental advantages over Excel, SAS, Stata, or SPSS:
R community is to share code under copyleft → ethical use of spending and algorithmsR is the statistical language par excellence, created by and for statisticians, with 6 fundamental advantages over Excel, SAS, Stata, or SPSS:
Automate → it will allow you to automate recurring tasks.
Replicability → you will be able to replicate your analysis in the same way every time.
Flexibility → you will be able to adapt the software to your needs.
Transparency → to be audited by the community.
One of the key ideas of R is the use of packages: codes that other people have implemented to solve a problem
Once installed, there are two ways to use a package (take it off the shelf)
library(), using the package name without quotes, we load the whole book into the sessionDuring your learning, it will be very common for things not to work out on the first try → you will be wrong. It will not only be important to accept it but also to read the error messages to learn from them.
A script will be the document in which we program, our .doc file (here with a .R extension) where we will write the commands. To open our first script, click on the menu in File < New File < R Script.
Be careful
It’s important not to overuse the console: everything you don’t write in a script, when you close, will be lost.
Be careful
R is case-sensitive: it is sensitive to uppercase and lowercase, so x and X represent different variables.
Now we have a fourth window: the window where we will write our codes. How do we run it?
Save current document.Ctrl+EnterJust as we usually work organized by folders on the computer, in RStudio we can do the same to work efficiently by creating projects.
A project will be a “folder” within RStudio, so our root directory will automatically be the project folder itself (allowing us to switch from one project to another using the top right menu).
We can create one in a new folder or in an existing folder.”
📝 Create a course folder on your computer and set up an RStudio Project inside it. This will serve as your working directory for the entire course. After creating the project, you will see an .Rproj file. Within this folder, create two subfolders: data (for datasets) and scripts (for the .R files from each session).
📝 Inside the project create a script Exercises-class1.R (inside the scripts folder). Once created, define in it a variable named a and whose value is -1. Execute the code in the (three) ways explained before.
📝 Add below another line to define a variable b with the value 5. Then save the multiplication of both variables. Execute the code as you want.
📝 Modify the code below to define two variables c and d, with values 3 and -1. Then divide the variables and save the result.
📝 Assign to x a positive value and then compute its square root; assign to y a negative number and compute its absolute value using abs().
Note that…
Commands like sqrt(), abs() or max() are what we call functions: lines of code that we have “encapsulated” under a name, and given some input arguments, execute the commands (a sort of shortcut). In the functions the arguments will ALWAYS be enclosed in parentheses
📝 Using the variable x already defined, complete/modify the code below to store in a new variable z the result stored in x minus 5.
📝 Define an x variable and assign it the value -1. Define another y and assign it the value 0. Then perform the operations a) x by y; b) square root of x. What do you get?
What data type can we have in each cell of a table?
Before we continue, it’s important to know something as soon as possible: starting with programming can be frustrating
Just like when learning a new language, the first obstacle is not so much what to say but how to say it correctly. The same goes for R, so let’s standardize our programming style as much as possible to avoid future errors.
R does not process spaces).snake_case.Tools < Global Options, you can customize some options in RStudio. In Code < Display, you can set Show margin to display an “imaginary” margin (not interacting with the code) to “force” you to make line breaks.RStudio, there’s a wonderful tool: if you type part of a variable or function name and press tab, RStudio will autocomplete it for you.Tools < Global Options < Code < Display and enable the Rainbow parentheses option.RStudio will notify you.class1.R in the project we created before)
See more tips at https://r4ds.had.co.nz/workflow-basics.html#whats-in-a-name
Are there variables beyond numbers in data science? For example, think about the data you might store about a person:
TRUE if enrolled or FALSE otherwise).The simplest data (which we’ve already used) will be numeric variables. To find out the data class in R of a variable, we use the class() function.
The simplest data type (we have already used it) will be the numeric variables. To know the data class in R of a variable we have the function class().
To know its typology (format) variable we have typeof().
[1] "double"
[1] "integer"
Note that…
In R we have a collection of functions starting with as.x() that serve as conversion functions: a data that was of one type, we convert it to type x.
In addition to the “common” numbers we will have the plus/minus infinity coded as Inf or -Inf.
With numeric variables we can perform the arithmetic operations of a calculator: adding (+)…
Let us imagine that, in addition to the age of a person we want to store his/her name: now the variable will be of type character.
The text strings are a type with which we obviously cannot perform arithmetic operations (other operations such as pasting or locating patterns can be performed).
Reminder
Text variables (character or string) are ALWAYS in quotes: TRUE (logical, binary value) is not the same as "TRUE" (text).
As we have commented R we will call function a piece of encapsulated code under a name, and which depends on some input arguments. Our first function will be paste(): given two strings, it allows us to paste them together.
Note that default pastes strings with a space, but we can add an optional argument to tell it the separator (in sep = ...).
Remember that functions are always as name_of_function(arguments), whereas we will use [i] to access to i-th element.
How do I know what arguments does a function need?
By typing ? paste in the console, you will get a help in the multipurpose panel, where you can see in its header what arguments the function already has default arguments assigned to it.
The arguments (and their detail) can also be consulted by tabulating (after a comma).
It is very important to understand the concept of default argument of a function in R: it is a value that the function uses but sometimes we may not see because already has a value assigned.
[1] "Javi Álvarez"
[1] "Javi Álvarez"
Note
The = operator is reserved for assigning arguments within functions. For all other assignments, we will use <-.
A more intuitive way to work with text is to use the {glue} package: the first thing to do is to “buy the book” (if we have never done it before). After that load the package
With the glue() function of that package we can use variables inside strings. For example, “age is … years old”, where the age is stored in a variable.
Another fundamental type will be the logical or binary variables (two values):
TRUE: true stored internally as a 1.
FALSE: false stored internally as a 0.
As we will see shortly, logical variables can actually take a third value: NA or missing data, representing not available, and it will be very common to find it within a database.
Logical values are usually the result of evaluate logical conditions. For example, imagine that we want to check whether a person is named Javi.
With the logical operator == we ask if what we have stored on the left is same as what we have on the right: we ASK
Note that…
It is not the same <- (assignment) as == (we are asking, it is a logical comparison).
In addition to “equal to” versus “different” comparisons, also order comparisons such as less than <, greater than >, <= or >=. Is the person less than 32 years old?
A very special data type: the date type data.
It looks like a simple text string but should represent an instant in time. What should happen if we add a 1 to a date?
Dates cannot be string/text: we must convert the text string to date.
Once installed, of all the packages (books) that we have, we will indicate it to load this one concretely.
To convert to date type we will use the as_date() function of the {lubridate} package (default in yyyy-mm-dd format).
In as_date() the default date format is yyyy-mm-dd so if the string is not entered correctly…
For any other format we must specify it in the optional argument format = ... such that %d represents days, %m months, %Y in 4-year format and %y in 2-year format.
In this package we have very useful functions for date management:
today() we can directly obtain the current date.More information
You have a pdf summary of the most important packages in the corresponding folder on campus
Try to perform the following exercises without looking at the solutions
📝 Define a variable that stores your age (called age) and another with your name (called name).
📝 Check with this variable age if it is NOT 60 years old or if it is called "Ornitorrinco" (you must obtain logical variables as a result).
📝 Why does the lower code not produce an error?
📝 Define another variable called siblings that answers the question “do you have siblings?” and another variable that stores your date of birth (called birth_date).
📝 Define another variable with your last name (called surname) and use glue() to have, in a single variable called full_name, your first and last name separated by a comma.
📝 Calculate the days that have passed since your birth date until today (with the birth date defined in Exercise 4).
📝 Why does the lower code give an error?
📝 Why does the lower code not produce an error?
📝 What is stored in the variable “healthy” below?
Concatenating cells: vectors. First databases
When working with data, we often have columns that represent variables: we will refer to these as vectors, which are a concatenation of cells (values) of the same type (similar to a column in a table).
The simplest way to create a vector is with the c() function (c stands for concatenate), and you just need to input the elements within parentheses, separated by commas.
Tip
An individual number x <- 1 (or x <- c(1)) is actually a vector of length one –> everything we know how to do with a number, we can do with a vector of numbers.
The most common type of vector is numeric, specifically, the well-known numeric sequences (e.g., the days of the month), used among other things, to index loops.
The seq(start, end) function allows us to create a [**numeric sequence]**{.hl-yellow} from a starting element to an ending one, advancing one by one.
A shortcut is the 1:n command, which returns the same as seq(1, n).
If the starting element is greater than the ending one, it understands that the sequence is in descending order.
Sometimes we may want to define a sequence with a specific length.
[1] 1.000000 9.166667 17.333333 25.500000 33.666667 41.833333 50.000000
We might also want to generate a vector of n repeated elements.
A vector is a concatenation of elements of the same type, but they don’t necessarily have to be numbers. Let’s create a sample sentence.
What will happen if we concatenate elements of different types?
Note that since all elements must be of the same type, what R does is convert everything to text, violating the data integrity.
With numeric vectors, we can perform the same arithmetic operations as with numbers → a number is a vector (of length one).
What will happen if we add or subtract a value to a vector?
Vectors can also interact with each other, so we can define, for example, vector sums (element by element).
Since the operation (e.g., a sum) is performed element by element, what will happen if we add two vectors of different lengths?
A very common operation is to ask questions of the data using logical conditions. For example, if we define a vector of temperatures…
Which days were below 22 degrees?
This will return a logical vector, depending on whether each element meets the given condition (of the same length as the vector being queried).
Logical conditions can be combined in two ways:
&) to return TRUE.|).Another common operation is accessing or getting elements. The simplest way is to use the [i] operator (access the i-th element).
Since a number is just a vector of length one, this operation can also be applied using a vector of indices to select.
Tip
To access the last element without worrying about its position, you can pass the vector’s length as the index x[length(x)].
Sometimes, instead of selecting, we may want to remove elements. This is done with the same operation but using negative indexing: the opetator [-i] «un-select» the i-th element
[1] "hi" "how" "are" "you" "?"
[1] "hi" "are" "you" "?"
In many cases, we want to select or remove elements based on logical conditions, depending on the values, so we will pass the condition itself as the index (remember, x < 2 returns a logical vector).
We can also make use of statistical operations, such as sum(), which, given a vector, returns the sum of all its elements.
What happens when a data point is missing?
As we’ve mentioned, logical values are internally stored as 0 and 1, so we can use them in arithmetic operations.
For example, if we want to find out the number of elements that meet a condition (e.g., less than 3), those that do will be assigned a 1 (TRUE), and those that don’t will get a 0 (FALSE). Therefore, summing the logical vector will give us the number of elements that meet the condition.
Another common operation that can be useful is the cumulative sum with cumsum(), which, given a vector, returns a vector where each element is the sum of the first, the first plus the second, the first plus the second plus the third, and so on.
What happens when a data point is missing?
In the case of the cumulative sum, what happens is that from that point onward, all subsequent accumulated values will be missing.
Another common operation that can be useful is the difference (with delay) with diff() which, given a vector, returns a vector with the second minus the first, the third minus the second, the fourth minus the third…and so on.
Other common operations are mean, median, percentiles, etc.
Other common operations are mean, median, percentiles, etc.
Finally, a common action is to know sort values:
sort(): returns the sorted vector. By default from smallest to largest but with decreasing = TRUE we can change it.[1] 7 20 23 25 33 41 65 77 81
[1] 81 77 65 41 33 25 23 20 7
Try to perform the following exercises without looking at the solutions
📝 Define the vector x as the concatenation of the first 5 odd numbers. Calculate the length of the vector
📝 Access the third element of x. Access the last element (regardless of length, a code that can always be executed). Delete the first element.
📝 Get the elements of x greater than 4. Calculate the vector 1/x and store it in a variable.
📝 Create a vector representing the names of 5 people, one of whom is unknown.
📝 Find from the vector x of exercises above the elements greater (strictly) than 1 and less (strictly) than 7. Find a way to find out if all the elements are positive or not.
📝 Given the vector x <- c(1, -5, 8, NA, 10, -3, 9), why does its mean return not a number but what is shown in the code below?
📝 Given the vector x <- c(1, -5, 8, NA, 10, -3, 9), extract the elements occupying the locations 1, 2, 5, 6.
📝 Given the x vector of the previous exercise, which ones have a missing data? Hint: the is.something() functions check if the element is of type something (press tab).
📝 Define the vector x as the concatenation of the first 4 even numbers. Calculate the number of elements of x strictly less than 5.
📝 Calculate the vector 1/x and obtain the ordered version (from smallest to largest) in the two possible ways
When analyzing data we usually have several variables for each individual: we need a “table” to collect them. The most immediate option is matrices: concatenation of variables of same type and equal length.
Imagine we have heights and weights of 4 people. How to create a dataset with the two variables?
We can also build the matrix by rows with the rbind() function (concatenate - bind - by rows - r), although it is recommended to have each variable in column and individual in row as we will see later.
View(matrix).We can also “flip” (transposed matrix) with t().
In some cases we will want to get the total data for an individual (a particular row but all columns) or the values of a whole variable for all individuals (a particular column but all rows). To do so, we leave one of the indexes unfilled.
We can also define a matrix from a numeric vector, rearranging the values in the form of a matrix (knowing that the elements are placed by columns).
With matrices it is the same as with vectors: when we apply an arithmetic operation we do it element by element
We can also perform operations by columns/rows without loops with the apply() function, and we will indicate as arguments
MARGIN = 1 for rows, MARGIN = 2 for columns)Try to perform the following exercises without looking at the solutions
📝 Modify the code below to define an x matrix of ones, with 3 rows and 7 columns.
📝 To the above matrix, add 1 to each number in the matrix and divide the result by 5. Then calculate its transpose
📝 Why does the code below return such a warning message?
📝 Define the matrix x <- matrix(1:12, nrow = 4). Then get the data of the first individual, the data of the third variable, and the element (4, 1).
📝 Define a matrix of 2 variables and 3 individuals such that each variable captures the height and age of 3 persons, so that the age of the second person is unknown (absent). Then calculate the mean of each variable (we should get a number!).
Arrays have the same problem as vectors: if we put together data of different types, it data integrity is compromised as it converts them (see the code below: the ages and the TRUE/FALSE are converted to text).
In order to work with variables of different type we have in R what is known as data.frame: concatenation of variables of equal length but which can be of different type.
Since a data.frame is already an attempt at a database the variables are not mere mathematical vectors: they have a meaning and we can (we must) give them names that describe their meaning.
We have our first data set! (strictly speaking we can’t talk about a database but for the moment it looks like one). You can visualize it by typing its name in console or with View(table).
If we want to access its elements, being again tabulated data, we can access as in the matrices (not recommended): again we have two indexes (rows and columns, leaving free the one we don’t use)
ages single names birth_date
2 24 NA laura 1992-04-01
[1] "javi" "laura" "lucía"
[1] 24
But it also has the advantages of a database : we can access the variables by name (recommended since the variables can change position and now they have a meaning), putting the name of the table followed by the symbol $ (with the tab, a menu of columns to choose from will appear).
names(): shows us the variable namesIf we have one already created and we want to add a column it is as simple as using the data.frame() function we have already seen to concatenate the column. Let’s add for example a new variable, the number of siblings of each individual.
Tables in data.frame format have some limitations. The main one is that does not allow recursion: imagine that we define a database with heights and weights, and we want a third variable with the BMI.
Error in data.frame(height = c(1.7, 1.8, 1.6), weight = c(80, 75, 70), : object 'weight' not found
Hereafter we will use the tibble (enhanced data.frame) format from the {tibble} package.
data_tb <-
tibble("height" = c(1.7, 1.8, 1.6), "weight" = c(80, 75, 70), "BMI" = weight / (height^2))
class(data_tb)[1] "tbl_df" "tbl" "data.frame"
# A tibble: 3 × 3
height weight BMI
<dbl> <dbl> <dbl>
1 1.7 80 27.7
2 1.8 75 23.1
3 1.6 70 27.3
Las tablas en formato tibble nos permitirá una gestión más ágil, eficiente y coherente de los data, con 4 ventajas principales:
tribble().Tip
The {datapasta} package allows us to copy and paste tables from web pages and simple documents as a tribble. See more in https://milesmcbain.github.io/datapasta/articles/how-to-datapasta.html#pasting-a-table-as-a-formatted-tibble-definition-with-tribble_paste
R by default operations are done element to element.Try to perform the following exercises without looking at the solutions
📝 Load from the {datasets} package the airquality dataset (New York air quality variables from May through September 1973). Is the airquality dataset of type tibble? If not, convert it to tibble (look in the package documentation at https://tibble.tidyverse.org/index.html).
📝 Once converted to tibble get the name of the variables and the dimensions of the data set. How many variables are there? How many days have been measured?
📝 Filter only the data for the month of August. How to tell it that we want only the rows that meet a specific condition?
📝 Select those data that are not from July or August.
📝 Modify the following code to keep only the ozone and temperature variables (no matter what position they are).
📝 Select the temperature and wind data for August.
The National Health and Nutrition Examination Survey (NHANES) is a large, nationally representative program conducted in the United States to assess the health and nutritional status of adults and children. NHANES combines interviews, physical examinations, and laboratory measurements. NHANES is widely used in epidemiology, public health research, and policy analysis.
# A tibble: 6 × 15
ID SurveyYr Gender Age AgeDecade AgeMonths Race1 Race3 Education
<int> <fct> <fct> <int> <fct> <int> <fct> <fct> <fct>
1 51624 2009_10 male 34 " 30-39" 409 White <NA> High School
2 51624 2009_10 male 34 " 30-39" 409 White <NA> High School
3 51624 2009_10 male 34 " 30-39" 409 White <NA> High School
4 51625 2009_10 male 4 " 0-9" 49 Other <NA> <NA>
5 51630 2009_10 female 49 " 40-49" 596 White <NA> Some College
6 51638 2009_10 male 9 " 0-9" 115 White <NA> <NA>
# ℹ 6 more variables: MaritalStatus <fct>, HHIncome <fct>, HHIncomeMid <int>,
# Poverty <dbl>, HomeRooms <int>, HomeOwn <fct>
Try to answer the questions posed in the workbook intro-R
In the {datasets} package (already installed by default) we have several datasets and one of them is airquality. Below I have extracted 3 variables from that dataset (note that it is done with data$variable, that dollar will be important in the future).The data captures daily measurements (n = 153 observations) of air quality in New York, from May to September 1973. Six 6 variables were measured: ozone levels, solar radiation, wind, temperature, month and day.
Try to answer the questions posed in the workbook intro-R
We will consider the surveys.RData file in which we have all poll surveys for Spain from 1982 to 2019.
# A tibble: 139,944 × 8
date_elec pollster field_date_from field_date_to exit_poll size party
<date> <chr> <date> <date> <lgl> <dbl> <chr>
1 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 UCD
2 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 PSOE
3 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 PCE
4 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 AP
5 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 CIU
6 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 PA
7 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 EAJ-PNV
8 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 HB
9 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 ERC
10 1982-10-28 PSOE 1982-10-28 1982-10-28 TRUE 85300 EE
# ℹ 139,934 more rows
# ℹ 1 more variable: estimation <dbl>
Try to answer the questions posed in the workbook intro-R
Javier Álvarez Liébana • Course at Real Colegio Complutense at Harvard University